<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;

/**
 * 命令行路由器，可节省一些命令行配置代码
 *     php think cli {scene_name}
 *     php think cli {scene_name}  --msg='[{"storeNo":"", "days": 30}]'
 *
 *  php think cli stats_member
 */
class CliRouter extends Command
{
    protected function configure()
    {
        $this->setName('cli')
            ->addArgument('scene', Argument::OPTIONAL, "命令行应用场景")
            ->addOption('msg', null, Option::VALUE_OPTIONAL, "消息体必须 json 格式字符串")
            ->setDescription('命令行路由器');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {

        $begin = microtime(true);
        $scene = trim($input->getArgument('scene'));
        if (empty($scene)) {
            $output->writeln('修正数据场景必须');
            exit(0);
        }
        $msg = $input->getOption('msg');
        if ( ! empty($msg)) {
            $msg = json_decode($msg, true);
            if ( ! is_array($msg)) {
                $output->writeln('消息体必须是json字符串');
                exit(0);
            }
        }
        $conf = config('cli.' . $scene);
        if (empty($conf)) {
            $output->writeln('不支持的命令行场景，请在./config/cli.php 文件里面配置');
            exit(0);
        }
        //注入类处理自己的逻辑
        $loc = app($conf['class']);
        $output->writeln(date('Y-m-d H:i:s') . ' 开始执行');
        $res = $loc->run($output, (array) $msg);
        if ($res) {
            $output->writeln(date('Y-m-d H:i:s') . ' 执行成功');
        } else {
            $output->writeln(date('Y-m-d H:i:s') . ' 执行失败');
            echo $loc->getError();
            echo "\n";
        }
    }
}
